require "http"

class Api::V1::OrdersController < Api::V1::BaseController
  skip_before_action :authenticate_request!, only: [:notify, :alipay_notify]

  def index
    @orders = @current_user.orders.order("created_at DESC")
    if params[:state].presence
      @orders = @orders.where(state: params[:state])
    end
    @orders = @orders.order("created_at DESC").page(params[:page]).per(params[:per])
  end

  def show
    @order = Order.find params[:id]
    @service_url = URI.encode("http://www.hnxfsy.cn/mobile/chats?shop_name=#{@order.shop.blank? ? "" : @order.shop.name}&shop_id=#{@order.shop_id}&order_id=#{@order.id}&token=#{request.headers['Authorization'].split(' ').last}")
  end

  def new
    need_express = params[:need_express].nil? ? true : ActiveModel::Type::Boolean.new.cast(params[:need_express])
    
    if params[:sku_id].presence && params[:quantity].presence
      # 检查参数
      sku = Sku.find_by_id(params[:sku_id])
      quantity = params[:quantity].to_i
      if sku.blank? && sku.on_hand_count < quantity
        render json: { result: false, message: '未找到对应商品或库存不足.' }, status: :ok and return
      end

      # 初始化
      @total_fee = 0.0
      @total_quantity = 0
      @orders = []

      if params[:address_id].presence
        address = @current_user.addresses.where(id: params[:address_id]).first
      else
        address = @current_user.default_address
      end
      if address.blank?
        render json: { result: false, message: '该地址不存在.' }, status: :ok and return
      end
      if sku.spu.shop.province?
        if address.province_id != sku.spu.shop.province_id
          render json: { result: false, message: '该店铺不在此地区经营.' }, status: :ok and return
        end
      elsif sku.spu.shop.city?
        if address.city_id != sku.spu.shop.city_id
          render json: { result: false, message: '该店铺不在此地区经营.' }, status: :ok and return
        end
      elsif sku.spu.shop.district?
        if address.district_id != sku.spu.shop.district_id
          render json: { result: false, message: '该店铺不在此地区经营.' }, status: :ok and return
        end
      end

      # 运费计算
      if need_express
        fare_template = sku.spu.fare_template
        fare_modes = fare_template.fare_modes.where(is_default: false)
        if fare_modes.count <= 0
          fare_mode = fare_template.fare_modes.where(is_default: true).first
        else
          fare_mode = nil
          fare_modes.each do |mode|
            if mode.province_ids.include?(address.province_id)
              fare_mode = mode
            end
          end
          if fare_mode.blank?
            fare_mode = fare_template.fare_modes.where(is_default: true).first
          end
        end
        if fare_mode.blank?
          express_fee = 0.0
        else
          if quantity < fare_mode.first_n_piece
            express_fee = 0.0
          elsif quantity >= fare_mode.first_n_piece && quantity < fare_mode.second_n_piece
            express_fee = fare_mode.first_amount
          elsif quantity >= fare_mode.second_n_piece
            express_fee = fare_mode.first_amount + fare_mode.second_amount
          end
        end
      else
        express_fee = 0.0
      end
      # 运费计算结束

      # 订单初始化
      order = {
        shop_id: sku.spu.shop.id,
        shop_avatar: sku.spu.shop.avatar.url,
        shop_name: sku.spu.shop.name,
        total_fee: 0.0,
        total_quantity: 0,
        express_fee: express_fee,
        order_items: [],
        coupon_fee: 0.0,
        coupons: [],
      }
      sale_price = sku.spu.promotion ? sku.promotion_price : sku.sale_price
      if not @current_user.membership.blank?
        sale_price = sale_price * @current_user.membership.discount / 100
      end
      option_value_presentation = "规格:"
      sku.sku_option_values.each do |sku_option_value|
        option_value_presentation += "#{sku_option_value.option_value.presentation}、"
      end
      order[:order_items].push({
        spu_id: sku.spu.id,
        spu_avatar: sku.spu.avatar.url,
        spu_name: sku.spu.name,
        sku: option_value_presentation,
        quantity: quantity,
        sale_price: sale_price
      })
      order[:total_quantity] += quantity
      order[:total_fee] += sale_price * quantity
      @current_user.coupons.where(state: :usable).where("shop_id = ? OR shop_id IS NULL", sku.spu.shop.id).where("end_at >= ?", Time.now.to_datetime).each do |coupon|
        order[:coupons].push(coupon)
      end
      @orders.push(order)
      @total_quantity += order[:total_quantity]
      # 订单初始化结束
      # 优惠券计算开始
      coupon_fee = 0.0
      if params[:coupon_ids].presence
        coupon_ids = params[:coupon_ids].split(',')
        selected_coupons = Coupon.where(state: :usable).where("shop_id = ? OR shop_id IS NULL", sku.spu.shop.id).where("id IN (?) AND end_at >= ?", coupon_ids, Time.now.to_datetime)
        selected_coupons.each do |coupon|
          user_coupon = UserCoupon.where(user_id: @current_user.id, coupon_id: coupon.id).first
          if user_coupon.presence
            if order[:total_fee] >= coupon.full_money
              coupon_fee += coupon.money
            end
          end
        end
      end
      order[:coupon_fee] = coupon_fee
      order[:total_fee] = order[:total_fee] + order[:express_fee] - order[:coupon_fee]
      @total_fee += order[:total_fee]
      order_min_total_fee = Setting.fetch("order_min_total_fee").to_i
      if @total_fee < order_min_total_fee
        render json: { result: false, message: "订单总金额不能少于#{order_min_total_fee}." }, status: :ok and return
      end
      # 优惠券计算结束
    elsif params[:order_item_ids].presence
      order_item_ids = params[:order_item_ids].split(',')
      order_items = OrderItem.where(user_id: @current_user.id, on_cart: true).where("order_items.id IN (?)", order_item_ids)
      if order_items.count <= 0
        render json: { result: false, message: '未找到对应商品.' }, status: :ok and return
      end
      order_items_array = order_items.joins(:spu).group_by{ |o| o.spu.shop_id }
      @total_fee = 0.0
      @total_quantity = 0
      @orders = []

      if params[:address_id].presence
        address = @current_user.addresses.where(id: params[:address_id]).first
      else
        address = @current_user.default_address
      end
      if address.blank?
        render json: { result: false, message: '该地址不存在.' }, status: :ok and return
      end

      # 判断该地址是否能下单
      address_can_order = true

      order_items_array.each do |order_item_array|
        shop = Shop.find order_item_array[0]
        
        if shop.province?
          if address.province_id != shop.province_id
            address_can_order = false
            break
          end
        elsif shop.city?
          if address.city_id != shop.city_id
            address_can_order = false
            break
          end
        elsif shop.district?
          if address.district_id != shop.district_id
            address_can_order = false
            break
          end
        end

        # 运费计算开始
        express_fee = 0.0
        if need_express
          express_fee_array = []
          order_item_array[1].each do |order_item|
            fare_template = order_item.spu.fare_template
            fare_modes = fare_template.fare_modes.where(is_default: false)
            if fare_modes.count <= 0
              fare_mode = fare_template.fare_modes.where(is_default: true).first
            else
              fare_mode = nil
              fare_modes.each do |mode|
                if mode.province_ids.include?(address.province_id)
                  fare_mode = mode
                end
              end
              if fare_mode.blank?
                fare_mode = fare_template.fare_modes.where(is_default: true).first
              end
            end
            if fare_mode.blank?
              express_fee_array.push(0.0)
            else
              if order_item.quantity < fare_mode.first_n_piece
                express_fee_array.push(0.0)
              elsif order_item.quantity >= fare_mode.first_n_piece && order_item.quantity < fare_mode.second_n_piece
                express_fee_array.push(fare_mode.first_amount)
              elsif order_item.quantity >= fare_mode.second_n_piece
                express_fee_array.push(fare_mode.first_amount + fare_mode.second_amount)
              end
            end
          end
          express_fee = express_fee_array.max
        end
        # 运费计算结束

        order = {
          shop_id: shop.id,
          shop_avatar: shop.avatar.url,
          shop_name: shop.name,
          total_fee: 0.0,
          total_quantity: 0,
          express_fee: express_fee,
          order_items: [],
          coupon_fee: 0.0,
          coupons: [],
        }
        order_item_array[1].each do |order_item|
          order[:order_items].push({
            spu_id: order_item.spu.id,
            spu_avatar: order_item.spu.avatar.url,
            spu_name: order_item.spu.name,
            sku: order_item.option_value_presentation,
            quantity: order_item.quantity,
            sale_price: order_item.fee
          })
          order[:total_quantity] += order_item.quantity
          order[:total_fee] += order_item.fee * order_item.quantity

          order_item.spu.coupons.each do |coupon|
            order[:coupons].push(coupon)
          end
        end
        @orders.push(order)
        order_min_total_fee = Setting.fetch("order_min_total_fee").to_i
        if order[:total_fee] < order_min_total_fee
          render json: { result: false, message: "订单总金额不能少于#{order_min_total_fee}." }, status: :ok and return
        end
        @total_quantity += order[:total_quantity]

        # 优惠券计算开始
        coupon_fee = 0.0
        if params[:coupon_ids].presence
          coupon_ids = params[:coupon_ids].split(',')
          selected_coupons = Coupon.where(state: :usable).where("shop_id = ? OR shop_id IS NULL", shop.id).where("id IN (?) AND end_at >= ?", coupon_ids, Time.now.to_datetime)
          selected_coupons.each do |coupon|
            user_coupon = UserCoupon.where(user_id: @current_user.id, coupon_id: coupon.id).first
            if user_coupon.presence
              if order[:total_fee] >= coupon.full_money
                coupon_fee += coupon.money
              end
            end
          end
        end
        order[:coupon_fee] = coupon_fee
        # 优惠券计算结束
        order[:total_fee] = order[:total_fee] + order[:express_fee] - coupon_fee
        @total_fee += order[:total_fee]
      end

      if not address_can_order
        render json: { result: false, message: '有店铺不在此地区经营.' }, status: :ok and return
      end
    else
      render json: { result: false, message: '缺少参数.' }, status: :ok and return
    end
    
  end

  def create
    @need_express = params[:need_express].nil? ? true : ActiveModel::Type::Boolean.new.cast(params[:need_express])
    if params[:sku_id].presence && params[:quantity].presence
      # 检查参数
      sku = Sku.find_by_id(params[:sku_id])
      quantity = params[:quantity].to_i
      if sku.blank? && sku.on_hand_count < quantity
        render json: { result: false, message: '未找到对应商品或库存不足.' }, status: :ok and return
      end
      address = Address.find_by_id params[:address_id]
      if address.blank?
        render json: { result: false, message: '地址不存在.' }, status: :ok and return
      end
      # 运费计算
      if @need_express
        if params[:address_id].presence
          address = @current_user.addresses.where(id: params[:address_id]).first
        else
          address = @current_user.default_address
        end
        if address.blank?
          express_fee = 0.0
        else
          fare_template = sku.spu.fare_template
          fare_modes = fare_template.fare_modes.where(is_default: false)
          if fare_modes.count <= 0
            fare_mode = fare_template.fare_modes.where(is_default: true).first
          else
            fare_mode = nil
            fare_modes.each do |mode|
              if mode.province_ids.include?(address.province_id)
                fare_mode = mode
              end
            end
            if fare_mode.blank?
              fare_mode = fare_template.fare_modes.where(is_default: true).first
            end
          end
          if fare_mode.blank?
            express_fee = 0.0
          else
            if quantity < fare_mode.first_n_piece
              express_fee = 0.0
            elsif quantity >= fare_mode.first_n_piece && quantity < fare_mode.second_n_piece
              express_fee = fare_mode.first_amount
            elsif quantity >= fare_mode.second_n_piece
              express_fee = fare_mode.first_amount + fare_mode.second_amount
            end
          end
        end
      else
        express_fee = 0.0
      end
      # 运费计算结束
      sale_price = sku.spu.promotion ? sku.promotion_price : sku.sale_price
      if not @current_user.membership.blank?
        sale_price = sale_price * @current_user.membership.discount / 100
      end
      # 判断是否总金额达标
      order_min_total_fee = Setting.fetch("order_min_total_fee").to_i
      if (sale_price * quantity) < order_min_total_fee
        render json: { result: false, message: "订单总金额不能少于#{order_min_total_fee}." }, status: :ok and return
      end
      # 创建订单项
      begin
        order_item = OrderItem.new
        order_item.user_id = @current_user.id
        order_item.sku_id = sku.id
        order_item.spu_id = sku.spu.id
        order_item.spu_name = sku.spu.name
        order_item.fee = sale_price
        order_item.on_cart = false
        order_item.quantity = quantity
        order_item.state = :pending
        order_item.option_value_presentation = "规格:"
        sku.sku_option_values.each do |sku_option_value|
          order_item.option_value_presentation += "#{sku_option_value.option_value.presentation}、"
        end
        order_item.save
        @orders = []
        # 创建订单
        order = Order.new
        order.address = address.province.name + address.city.name + address.district.name + address.address
        order.buyer_phone = address.phone
        order.buyer_name = address.sendee
        order.user_id = @current_user.id
        order.shop_id = sku.spu.shop.id
        order.state = :pending
        order.express_fee = express_fee
        order.trade_no = Time.now.strftime('%Y%m%d%H%M%S') + rand(999).to_s
        order.save!
        total_fee = 0
        # 更新订单项
        order_item.update_attributes(order_id: order.id)
        order_item.spu.sales_volume += 1
        order_item.spu.stock -= 1
        order_item.spu.save!
        total_fee = total_fee + order_item.fee * order_item.quantity

        # 优惠券计算开始
        coupon_fee = 0.0
        if params[:coupon_ids].presence
          coupon_ids = params[:coupon_ids].split(',')
          selected_coupons = Coupon.where(state: :usable).where("shop_id = ? OR shop_id IS NULL", sku.spu.shop.id).where("id IN (?) AND end_at >= ?", coupon_ids, Time.now.to_datetime)
          selected_coupons.each do |coupon|
            user_coupon = UserCoupon.where(user_id: @current_user.id, coupon_id: coupon.id).first
            if user_coupon.presence
              if total_fee >= coupon.full_money
                coupon_fee += coupon.money
              end
            end
          end
        end
        # 优惠券计算结束
        order.update_attributes!(total_fee: total_fee + express_fee - coupon_fee, coupon_fee: coupon_fee)
        # 推入数组
        @orders.push(order)
      rescue => exception
        render json: { result: false, message: '下单失败.', data: {} }, status: :ok
      end
    elsif params[:order_item_ids].presence
      order_item_ids = params[:order_item_ids].split(',')
      order_items = OrderItem.where(user_id: @current_user.id, on_cart: true).where("order_items.id IN (?)", order_item_ids)
      if order_items.count <= 0
        render json: { result: false, message: '未找到对应商品.' }, status: :ok and return
      end
      address = Address.find_by_id params[:address_id]
      if address.blank?
        render json: { result: false, message: '地址不存在.' }, status: :ok and return
      end
      order_items_array = order_items.joins(:spu).group_by{ |o| o.spu.shop_id }

      # 判断是否总金额达标
      order_min_total_fee = Setting.fetch("order_min_total_fee").to_i
      order_items_array.each do |order_item_array|
        temp_total_fee = 0
        order_item_array[1].each do |order_item|
          temp_total_fee = temp_total_fee + order_item.fee * order_item.quantity
        end
        if temp_total_fee < order_min_total_fee
          render json: { result: false, message: "订单总金额不能少于#{order_min_total_fee}." }, status: :ok and return
        end
      end

      begin
        @orders = []
        order_items_array.each do |order_item_array|
          # 运费计算开始
          if @need_express
            express_fee_array = []
            order_item_array[1].each do |order_item|
              fare_template = order_item.spu.fare_template
              fare_modes = fare_template.fare_modes.where(is_default: false)
              if fare_modes.count <= 0
                fare_mode = fare_template.fare_modes.where(is_default: true).first
              else
                fare_mode = nil
                fare_modes.each do |mode|
                  if mode.province_ids.include?(address.province_id)
                    fare_mode = mode
                  end
                end
                if fare_mode.blank?
                  fare_mode = fare_template.fare_modes.where(is_default: true).first
                end
              end
              if fare_mode.blank?
                express_fee_array.push(0.0)
              else
                if order_item.quantity < fare_mode.first_n_piece
                  express_fee_array.push(0.0)
                elsif order_item.quantity >= fare_mode.first_n_piece && order_item.quantity < fare_mode.second_n_piece
                  express_fee_array.push(fare_mode.first_amount)
                elsif order_item.quantity >= fare_mode.second_n_piece
                  express_fee_array.push(fare_mode.first_amount + fare_mode.second_amount)
                end
              end
            end
            express_fee = express_fee_array.max
          else
            express_fee = 0.0
          end
          # 运费计算结束
          order = Order.new
          order.address = address.province.name + address.city.name + address.district.name + address.address
          order.buyer_phone = address.phone
          order.buyer_name = address.sendee
          order.user_id = @current_user.id
          order.shop_id = order_item_array[0]
          order.state = :pending
          order.express_fee = express_fee
          order.trade_no = Time.now.strftime('%Y%m%d%H%M%S') + rand(999).to_s
          order.save!
          total_fee = 0.0
          order_item_array[1].each do |order_item|
            order_item.update_attributes(order_id: order.id, on_cart: false)
            order_item.spu.sales_volume += 1
            order_item.spu.stock -= 1
            order_item.spu.save!
            total_fee = total_fee + order_item.fee * order_item.quantity
          end
          # 优惠券计算开始
          coupon_fee = 0.0
          if params[:coupon_ids].presence
            coupon_ids = params[:coupon_ids].split(',')
            selected_coupons = Coupon.where(state: :usable).where("shop_id = ? AND id IN (?) AND end_at >= ?", order.shop_id, coupon_ids, Time.now.to_datetime)
            selected_coupons.each do |coupon|
              user_coupon = UserCoupon.where(user_id: @current_user.id, coupon_id: coupon.id).first
              if user_coupon.presence
                if total_fee >= coupon.full_money
                  coupon_fee += coupon.money
                end
              end
            end
          end
          # 优惠券计算结束
          order.update_attributes!(total_fee: total_fee + express_fee - coupon_fee, coupon_fee: coupon_fee)
          @orders.push(order)
        end
      rescue => exception
        render json: { result: false, message: '下单失败.', data: {} }, status: :ok
      end
    else
      render json: { result: false, message: '缺少参数.' }, status: :ok and return
    end
    
  end

  def update
    @order = Order.find params[:id]
    @order.state = params[:state]
    if @order.save
      render json: { result: true, message: '更新成功.' }, status: :ok
    else
      render json: { result: false, message: '更新失败.' }, status: :ok
    end
  end

  def success
    @order = Order.find params[:id]
    if @order.user_id != @current_user.id
      render json: { result: false, message: '该订单不能操作.' }, status: :ok and return
    end
  end

  def evaluate
    @order = Order.find params[:id]
    if @current_user.id != @order.user_id
      render json: { result: false, message: '无权操作该订单.' }, status: :ok
    end
    @order_items = @order.order_items.where(is_evaluated: false)
  end

  def complete
    @order = Order.find params[:id]
    if @order.sent? && @order.user_id == @current_user.id
      if @order.update(state: :completed)
        @order.order_items.update_all(state: :completed)
        render json: { result: true, message: '确认收货成功.' }, status: :ok
      else
        render json: { result: false, message: '确认收货失败.' }, status: :ok
      end
    else
      render json: { result: false, message: '该订单不能操作.' }, status: :ok
    end
  end

  def cancel
    @order = Order.find params[:id]
    if @order.pending? && @order.user_id == @current_user.id
      if @order.update(state: :cancel)
        @order.order_items.update_all(state: :unchange)
        @order.send_notify("订单已取消.", 'Native', 'order_details', '{ "id": ' + @order.id.to_s + ' }')
        render json: { result: true, message: '取消成功.' }, status: :ok
      else
        render json: { result: false, message: '取消失败.' }, status: :ok
      end
    else
      render json: { result: false, message: '该订单不能取消.' }, status: :ok
    end
  end

  def refund
    @order = Order.find params[:id]
    if @order.checkouted? && @order.user_id == @current_user.id
      refund_no = "R#{Time.now.strftime('%Y%m%d%H%M%S') + rand(999).to_s}"
      if @order.update(state: :cancel, refund_no: refund_no)
        @order.order_items.update_all(state: :unchange)
        if @order.wepay?
          if @order.mix_trade_no.blank?
            refund_params = {
              out_trade_no: @order.trade_no,
              out_refund_no: refund_no,
              total_fee: (@order.total_fee * 100).to_i,
              refund_fee: (@order.total_fee * 100).to_i
            }
          else
            refund_params = {
              out_trade_no: @order.mix_trade_no,
              out_refund_no: refund_no,
              total_fee: (@order.total_fee * 100).to_i,
              refund_fee: (@order.total_fee * 100).to_i
            }
          end
          result_code = WxPay::Service.invoke_refund refund_params
          @order.shop.update(balance: @order.shop.balance - @order.total_fee)
          @order.send_notify("订单已退款.", 'Native', 'order_details', '{ "id": ' + @order.id.to_s + ' }')
          render json: { result: true, message: '取消成功.', data: { result_code: result_code } }, status: :ok
        elsif @order.alipay?
          @client = Alipay::Client.new(
            url: Figaro.env.alipay_url,
            app_id: Figaro.env.alipay_app_id,
            app_private_key: Figaro.env.alipay_app_private_key,
            alipay_public_key: Figaro.env.alipay_public_key
          )
          if @order.mix_trade_no.blank?
            response = @client.execute(
              method: 'alipay.trade.refund',
              biz_content: {
                out_trade_no: @order.trade_no,
                refund_amount: "#{@order.total_fee}"
              }.to_json(ascii_only: true)
            )
          else
            response = @client.execute(
              method: 'alipay.trade.refund',
              biz_content: {
                out_trade_no: @order.mix_trade_no,
                out_request_no: @order.trade_no,
                refund_amount: "#{@order.total_fee}"
              }.to_json(ascii_only: true)
            )
          end
          # 取得结果
          result_code = JSON.parse(response)["alipay_trade_refund_response"]["code"]
          result_sub_code = JSON.parse(response)["alipay_trade_refund_response"]["sub_code"]
          # => '10000'
          result_fund_change = JSON.parse(response)["alipay_trade_refund_response"]["fund_change"]
          # => 'Y'
          @order.shop.update(balance: @order.shop.balance - @order.total_fee)
          @order.send_notify("订单已退款.", 'Native', 'order_details', '{ "id": ' + @order.id.to_s + ' }')
          render json: { result: true, message: '取消成功.', data: { result_code: result_code, result_sub_code: result_sub_code } }, status: :ok
        elsif @order.moneybag?
          @order.shop.update(balance: @order.shop.balance - @order.total_fee)
          @order.user.update(moneybag: @order.user.moneybag + @order.total_fee)
          @order.send_notify("订单已退款.", 'Native', 'order_details', '{ "id": ' + @order.id.to_s + ' }')
          render json: { result: true, message: '取消成功.', data: { } }, status: :ok
        else
          @order.update(state: :checkouted)
          render json: { result: false, message: '找不到支付方式.' }, status: :ok
        end
      else
        render json: { result: false, message: '取消失败.' }, status: :ok
      end
    else
      render json: { result: false, message: '该订单不能退款.' }, status: :ok
    end
  end

  def after_sale
    @order = Order.find params[:id]
    if (@order.sent? || @order.checkouted?) && @order.user_id == @current_user.id
    else
      render json: { result: false, message: '该订单不能申请售后.' }, status: :ok
    end
  end

  def destroy
    @order = Order.find params[:id]
    if @order.cancel? && @order.user_id == @current_user.id
      if @order.destroy
        render json: { result: true, message: '删除成功.' }, status: :ok
      else
        render json: { result: false, message: '删除失败.' }, status: :ok
      end
    else
      render json: { result: false, message: '该订单不能取消.' }, status: :ok
    end
  end

  def notify
    result = Hash.from_xml(request.body.read)["xml"]
  
    if WxPay::Sign.verify?(result)
      send_phone = ''
      send_shop = ''
      if result["out_trade_no"][0, 2] == 'MP'
        orders = Order.where(mix_trade_no: result["out_trade_no"])
        orders.each do |order|
          order.update_attributes(state: :checkouted)
          order.order_items.update_all(state: :checkouted)
          order.shop.update(balance: order.shop.balance + order.total_fee)
          order.send_notify("支付成功.", 'Native', 'order_details', '{ "id": ' + order.id.to_s + ' }')
          order.compute_bonus
          send_phone = order.shop.phone
        end
      else
        order = Order.find_by_trade_no(result["out_trade_no"])
        order.update_attributes(state: :checkouted)
        order.order_items.update_all(state: :checkouted)
        order.shop.update(balance: order.shop.balance + order.total_fee)
        order.send_notify("支付成功.", 'Native', 'order_details', '{ "id": ' + @order.id.to_s + ' }')
        order.compute_bonus
        send_phone = order.shop.phone
      end
      @reponse = Qcloud::Sms.single_sender(send_phone, "271384", ["#{result["out_trade_no"]}"])
      render :xml => {return_code: "SUCCESS"}.to_xml(root: 'xml', dasherize: false)
    else
      render :xml => {return_code: "FAIL", return_msg: "签名失败"}.to_xml(root: 'xml', dasherize: false)
    end
  end

  def alipay_notify
    @client = Alipay::Client.new(
      url: Figaro.env.alipay_url,
      app_id: Figaro.env.alipay_app_id,
      app_private_key: Figaro.env.alipay_app_private_key,
      alipay_public_key: Figaro.env.alipay_public_key
    )
    Rails.logger.error request.request_parameters
    Rails.logger.error @client.verify?(request.request_parameters)
    if @client.verify?(request.request_parameters)
      Rails.logger.error "verify right"
      send_phone = ''
      send_shop = ''
      if params[:out_trade_no][0, 2] == 'MP'
        Rails.logger.error "order = MP"
        orders = Order.where(mix_trade_no: params[:out_trade_no])
        orders.each do |order|
          order.update_attributes(state: :checkouted)
          order.order_items.update_all(state: :checkouted)
          order.shop.update(balance: order.shop.balance + order.total_fee)
          order.send_notify("支付成功.", 'Native', 'order_details', '{ "id": ' + order.id.to_s + ' }')
          order.compute_bonus
          send_phone = order.shop.phone
        end
      else
        Rails.logger.error "order != MP"
        order = Order.find_by_trade_no(params[:out_trade_no])
        order.update_attributes(state: :checkouted)
        order.order_items.update_all(state: :checkouted)
        order.shop.update(balance: order.shop.balance + order.total_fee)
        order.send_notify("支付成功.", 'Native', 'order_details', '{ "id": ' + @order.id.to_s + ' }')
        order.compute_bonus
        send_phone = order.shop.phone
      end
      @reponse = Qcloud::Sms.single_sender(send_phone, "271384", ["#{params[:out_trade_no]}"])
      render plain: 'success'
    else
      Rails.logger.error "verify error"
      render plain: 'error'
    end
  end

  def wechat_refund_notify
  end

  def alipay_refund_notify
    
  end

end
